package com.gaozhaoyang.upload;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@WebServlet("/upload")
@MultipartConfig
public class UploadServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.根据文件名称获取文件资源
        Part part = req.getPart("fileName");
        //2.从文件资源中获取文件名
        String fileName = part.getSubmittedFileName();
        //3.重命名文件名
        fileName = UUID.randomUUID() + fileName;
        //4.组装一个写入地址
        File file = new File("h:/upload");
            //判断是否已经存在该文件夹
            if (!file.exists()){
                //如果不存在就创建一个
                file.mkdir();
            }
            //文件名字
        String path = file + "/" + fileName;
        //5.将文件写入该文件夹下
        part.write(path);
    }
}
